import React, { useEffect } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { AppDispatch } from './store'
import { getCurrentUser, selectIsAuthenticated, selectUser } from './store/slices/authSlice'

// Layout components
import { PublicLayout } from './components/layout/PublicLayout'
import { DeveloperLayout } from './components/layout/DeveloperLayout'
import { AdminLayout } from './components/layout/AdminLayout'

// Auth pages
import { LoginPage } from './pages/auth/LoginPage'
import { RegisterPage } from './pages/auth/RegisterPage'
import { VerifyEmailPage } from './pages/auth/VerifyEmailPage'
import { ForgotPasswordPage } from './pages/auth/ForgotPasswordPage'
import { ResetPasswordPage } from './pages/auth/ResetPasswordPage'

// Public pages
import { HomePage } from './pages/marketplace/HomePage'
import { MarketplacePage } from './pages/marketplace/MarketplacePage'
import { PluginDetailPage } from './pages/marketplace/PluginDetailPage'

// Developer pages
import { DeveloperDashboard } from './pages/developer/DeveloperDashboard'
import { MyPluginsPage } from './pages/developer/MyPluginsPage'
import { CreatePluginPage } from './pages/developer/CreatePluginPage'
import { EditPluginPage } from './pages/developer/EditPluginPage'
import { PluginAnalyticsPage } from './pages/developer/PluginAnalyticsPage'
import { ApiKeysPage } from './pages/developer/ApiKeysPage'
import { DeveloperSettingsPage } from './pages/developer/DeveloperSettingsPage'

// Admin pages
import { AdminDashboard } from './pages/admin/AdminDashboard'
import { UserManagementPage } from './pages/admin/UserManagementPage'
import { PluginManagementPage } from './pages/admin/PluginManagementPage'
import { SecurityMonitoringPage } from './pages/admin/SecurityMonitoringPage'
import { AuditLogsPage } from './pages/admin/AuditLogsPage'
import { SystemSettingsPage } from './pages/admin/SystemSettingsPage'

// Protected route component
interface ProtectedRouteProps {
  children: React.ReactNode
  requireAuth?: boolean
  requireAdmin?: boolean
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ 
  children, 
  requireAuth = true, 
  requireAdmin = false 
}) => {
  const isAuthenticated = useSelector(selectIsAuthenticated)
  const user = useSelector(selectUser)

  if (requireAuth && !isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  if (requireAdmin && user?.role !== 'admin') {
    return <Navigate to="/developer" replace />
  }

  return <>{children}</>
}

function App() {
  const dispatch = useDispatch<AppDispatch>()
  const isAuthenticated = useSelector(selectIsAuthenticated)
  const user = useSelector(selectUser)

  // Initialize app - check for existing auth
  useEffect(() => {
    const token = localStorage.getItem('accessToken')
    if (token && !user) {
      dispatch(getCurrentUser())
    }
  }, [dispatch, user])

  return (
    <div className="App">
      <Routes>
        {/* Public routes */}
        <Route path="/" element={<PublicLayout />}>
          <Route index element={<HomePage />} />
          <Route path="marketplace" element={<MarketplacePage />} />
          <Route path="plugins/:id" element={<PluginDetailPage />} />
        </Route>

        {/* Auth routes */}
        <Route path="/login" element={
          isAuthenticated ? <Navigate to="/developer" replace /> : <LoginPage />
        } />
        <Route path="/register" element={
          isAuthenticated ? <Navigate to="/developer" replace /> : <RegisterPage />
        } />
        <Route path="/auth/verify-email" element={<VerifyEmailPage />} />
        <Route path="/forgot-password" element={<ForgotPasswordPage />} />
        <Route path="/auth/reset-password" element={<ResetPasswordPage />} />

        {/* Developer routes */}
        <Route path="/developer" element={
          <ProtectedRoute>
            <DeveloperLayout />
          </ProtectedRoute>
        }>
          <Route index element={<DeveloperDashboard />} />
          <Route path="plugins" element={<MyPluginsPage />} />
          <Route path="plugins/new" element={<CreatePluginPage />} />
          <Route path="plugins/:id/edit" element={<EditPluginPage />} />
          <Route path="plugins/:id/analytics" element={<PluginAnalyticsPage />} />
          <Route path="api-keys" element={<ApiKeysPage />} />
          <Route path="settings" element={<DeveloperSettingsPage />} />
        </Route>

        {/* Admin routes */}
        <Route path="/admin" element={
          <ProtectedRoute requireAdmin>
            <AdminLayout />
          </ProtectedRoute>
        }>
          <Route index element={<AdminDashboard />} />
          <Route path="users" element={<UserManagementPage />} />
          <Route path="plugins" element={<PluginManagementPage />} />
          <Route path="security" element={<SecurityMonitoringPage />} />
          <Route path="audit-logs" element={<AuditLogsPage />} />
          <Route path="settings" element={<SystemSettingsPage />} />
        </Route>

        {/* Catch all route */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </div>
  )
}

export default App
